package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"strings"
	"time"

	"github.com/xuri/excelize/v2"
)

type Shop struct {
	ShopName             string `json:"shop_name"`
	ShopID               string `json:"shop_id"`
	EnCenterVersionCode  string `json:"en_center_version_code"`
	EnCenterStartTime    string `json:"en_center_start_time"`
	EnCenterEndTime      string `json:"en_center_end_time"`
	PlatVersionCode      string `json:"plat_version_code"`
	PlatVersionStartTime string `json:"plat_version_start_time"`
	PlatVersionEndTime   string `json:"plat_version_end_time"`
}

var dir = "/Users/gyl/Documents/gostudy/txt_to_excel/"

func main() {
	startTime := time.Now()
	fmt.Println("开始处理数据...")

	filterDate := time.Date(2025, time.May, 26, 0, 0, 0, 0, time.UTC)
	seen := make(map[string]struct{})
	var shops []Shop
	files := []string{dir + "output.txt", dir + "output2.txt", dir + "output3.txt", dir + "output4.txt", dir + "output5.txt", dir + "output6.txt", dir + "output7.txt"}

	// 文件处理进度
	totalFiles := len(files)
	for i, file := range files {
		fmt.Printf("\n▶ 正在处理文件 %d/%d: %s\n", i+1, totalFiles, file)

		content, err := ioutil.ReadFile(file)
		if err != nil {
			fmt.Printf("❌ 文件读取失败: %v\n", err)
			continue
		}
		// 添加文件内容处理进度
		processContent(string(content), &shops, seen, filterDate, file)
	}

	fmt.Printf("\n✅ 所有文件处理完成！共发现有效数据 %d 条\n", len(shops))
	exportToExcel(shops)
	fmt.Printf("总耗时: %.2f秒\n", time.Since(startTime).Seconds())
}

func processContent(content string, shops *[]Shop, seen map[string]struct{}, filterDate time.Time, filename string) {
	lines := strings.Split(content, "\n")
	totalLines := len(lines)
	var jsonBuffer strings.Builder
	collecting := false
	processedBlocks := 0

	for lineNum, line := range lines {
		trimmed := strings.TrimSpace(line)
		if trimmed == "" {
			continue
		}

		// 显示行处理进度（每1000行或最后一行）
		if (lineNum+1)%1000 == 0 || lineNum == totalLines-1 {
			fmt.Printf("▏ 文件 %s 处理进度: %d/%d 行 (%.1f%%) \r",
				filename,
				lineNum+1,
				totalLines,
				float64(lineNum+1)/float64(totalLines)*100,
			)
		}

		switch {
		case strings.HasPrefix(trimmed, "["):
			collecting = true
			jsonBuffer.Reset()
			jsonBuffer.WriteString(trimmed)
			if strings.HasSuffix(trimmed, "]") {
				parseJSON(jsonBuffer.String(), shops, seen, filterDate)
				collecting = false
				processedBlocks++
			}

		case collecting:
			jsonBuffer.WriteString(trimmed)
			if strings.Contains(trimmed, "]") {
				collecting = false
				parseJSON(jsonBuffer.String(), shops, seen, filterDate)
				processedBlocks++
			}
		}
	}
	fmt.Printf("\n▏ 文件 %s 完成，解析到 %d 个数据块\n", filename, processedBlocks)
}

func parseJSON(jsonStr string, shops *[]Shop, seen map[string]struct{}, filterDate time.Time) {
	var parsedShops []Shop
	if err := json.Unmarshal([]byte(jsonStr), &parsedShops); err != nil {
		fmt.Printf("❌ JSON解析错误: %v\n", err)
		return
	}

	validCount := 0
	skipped := 0
	chongfu := 0
	guoqi := 0
	for _, shop := range parsedShops {
		endTime, err := time.Parse("2006-01-02", shop.EnCenterEndTime)
		if err != nil || endTime.Before(filterDate) {
			skipped++
			guoqi++
			continue
		}

		key := fmt.Sprintf("%s|%s|%s|%s|%s|%s|%s|%s",
			shop.ShopName,
			shop.ShopID,
			shop.EnCenterVersionCode,
			shop.EnCenterStartTime,
			shop.EnCenterEndTime,
			shop.PlatVersionCode,
			shop.PlatVersionStartTime,
			shop.PlatVersionEndTime,
		)

		if _, exists := seen[key]; !exists {
			seen[key] = struct{}{}
			*shops = append(*shops, shop)
			validCount++
		} else {
			skipped++
			chongfu++
		}
	}
	fmt.Printf("▏ 解析到数据块：原始 %d 条 | 有效 %d 条 | 跳过 %d 条（重复:%d/过期 %d）\n",
		len(parsedShops),
		validCount,
		skipped,
		chongfu,
		guoqi,
	)
}

func exportToExcel(shops []Shop) {
	fmt.Printf("\n开始导出数据到Excel...\n")

	f := excelize.NewFile()
	defer f.Close()

	index, _ := f.NewSheet("Sheet1")
	f.SetActiveSheet(index)

	// 设置标题
	headers := []string{"店铺名称", "店铺ID", "企业平台版本", "企业平台开始时间", "企业平台结束时间", "机器人平台版本", "机器人平台开始时间", "机器人平台结束时间"}
	for col, header := range headers {
		cell, _ := excelize.CoordinatesToCellName(col+1, 1)
		f.SetCellValue("Sheet1", cell, header)
	}

	// 添加导出进度
	totalRows := len(shops)
	for row, shop := range shops {
		// 每100行或最后一行显示进度
		if (row+1)%100 == 0 || row == totalRows-1 {
			fmt.Printf("▏ 导出进度: %d/%d 行 (%.1f%%) \r",
				row+1,
				totalRows,
				float64(row+1)/float64(totalRows)*100,
			)
		}

		data := []string{
			shop.ShopName,
			shop.ShopID,
			shop.EnCenterVersionCode,
			shop.EnCenterStartTime,
			shop.EnCenterEndTime,
			shop.PlatVersionCode,
			shop.PlatVersionStartTime,
			shop.PlatVersionEndTime,
		}
		for col, value := range data {
			cell, _ := excelize.CoordinatesToCellName(col+1, row+2)
			f.SetCellValue("Sheet1", cell, value)
		}
	}

	if err := f.SaveAs(dir + "腾讯云.xlsx"); err != nil {
		fmt.Printf("\n❌ Excel保存失败: %v", err)
		os.Exit(1)
	}
	fmt.Printf("\n✅ 导出成功！保存路径: %s腾讯云.xlsx\n", dir)
}
